<template>
  <div class="tree-graph-container">
    <el-card>
      <div slot="header">
        <span>族谱树视图</span>
        <el-select 
          v-model="selectedBranchId" 
          placeholder="选择分支" 
          style="width: 200px; margin-left: 20px;"
          @change="onBranchChange"
          clearable
        >
          <el-option label="全部分支" :value="null" />
          <el-option 
            v-for="branch in branches" 
            :key="branch.id" 
            :label="branch.name" 
            :value="branch.id" 
          />
        </el-select>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">
          刷新
        </el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <i class="el-icon-loading"></i>
        <p>正在加载族谱数据...</p>
      </div>
      
      <div v-else-if="!treeData" class="empty-container">
        <i class="el-icon-warning"></i>
        <p>暂无族谱数据</p>
        <el-button type="primary" @click="refreshData">重新加载</el-button>
      </div>
      
      <div v-else ref="chart" class="tree-chart-container">
        <ul v-if="contextMenu.visible" :style="contextMenuStyle" class="context-menu">
          <li @click="onMenu('add')">新增子成员</li>
          <li @click="onMenu('edit')">编辑成员</li>
          <li @click="onMenu('delete')">删除成员</li>
        </ul>
        <div
          v-if="dragState.dragging"
          :style="dragHintStyle"
          class="drag-hint"
        >
          拖到目标节点释放以调整父子关系
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getEnhancedTreeChildren } from '@/api/member';
import { getBranchList } from '@/api/branch';

export default {
  name: 'FamilyTreeGraph',
  data() {
    return {
      loading: false,
      treeData: null,
      chart: null,
      contextMenu: {
        visible: false,
        x: 0,
        y: 0,
        node: null
      },
      dragState: {
        dragging: false,
        draggedNode: null,
        mouseX: 0,
        mouseY: 0
      },
      // 新增：分支相关数据
      branches: [],
      selectedBranchId: null
    };
  },
  computed: {
    contextMenuStyle() {
      return {
        position: 'absolute',
        left: this.contextMenu.x + 'px',
        top: this.contextMenu.y + 'px',
        zIndex: 1000
      };
    },
    dragHintStyle() {
      return {
        position: 'fixed',
        left: this.dragState.mouseX + 10 + 'px',
        top: this.dragState.mouseY + 10 + 'px',
        zIndex: 2000,
        background: '#fffbe6',
        border: '1px solid #ffe58f',
        padding: '4px 12px',
        borderRadius: '4px',
        color: '#d48806',
        pointerEvents: 'none'
      };
    }
  },
  async mounted() {
    await this.loadBranches();
    await this.loadData();
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
    document.addEventListener('click', this.hideMenu);
    document.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('mouseup', this.handleMouseUp);
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.resizeChart);
    document.removeEventListener('click', this.hideMenu);
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
  },
  methods: {
    // 新增：加载分支列表
    async loadBranches() {
      try {
        const res = await getBranchList()
        this.branches = res.records || []
      } catch (error) {
        console.error('加载分支列表失败:', error)
      }
    },
    
    // 新增：分支切换处理
    onBranchChange() {
      this.refreshData()
    },
    
    // 新增：递归加载完整的树形结构
    async loadCompleteTree() {
      this.loading = true;
      try {
        // 首先加载根节点
        // 当选择"全部分支"时，selectedBranchId 为 null，应该不传递分支参数
        const branchId = this.selectedBranchId === null ? undefined : this.selectedBranchId
        const rootNodes = await getEnhancedTreeChildren(null, branchId);
        console.log('Root nodes:', rootNodes);
        
        // 递归加载每个根节点的完整子树
        const completeTree = [];
        for (const rootNode of rootNodes) {
          const completeNode = await this.loadNodeWithChildren(rootNode);
          completeTree.push(completeNode);
        }
        
        this.treeData = completeTree;
        console.log('Complete tree data:', this.treeData);
      } catch (error) {
        this.$message.error('加载族谱数据失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
    
    // 新增：递归加载节点及其所有子节点
    async loadNodeWithChildren(node) {
      const result = {
        ...node,
        children: []
      };
      
      // 如果不是叶子节点，加载子节点
      if (!node.isLeaf) {
        try {
          // 当选择"全部分支"时，selectedBranchId 为 null，应该不传递分支参数
          const branchId = this.selectedBranchId === null ? undefined : this.selectedBranchId
          const children = await getEnhancedTreeChildren(node.id, branchId);
          console.log(`Children of ${node.name}:`, children);
          
          // 递归加载每个子节点
          for (const child of children) {
            const completeChild = await this.loadNodeWithChildren(child);
            result.children.push(completeChild);
          }
        } catch (error) {
          console.error(`Error loading children for ${node.name}:`, error);
        }
      }
      
      return result;
    },
    
    async loadData() {
      await this.loadCompleteTree();
    },
    
    async refreshData() {
      await this.loadData();
      this.initChart();
    },
    
    resizeChart() {
      if (this.chart) this.chart.resize();
    },
    initChart() {
      if (!this.treeData || this.treeData.length === 0) return;
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
        this.chart.on('click', params => {
          if (params.data) {
            this.$emit('node-click', params.data.origin || params.data);
          }
        });
        this.chart.getZr().on('contextmenu', this.handleContextMenu);
      }
      
      // 转换数据为 ECharts 格式
      const seriesData = this.convertToEChartsData(this.treeData);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return params.data.name;
          }
        },
        series: [{
          type: 'tree',
          data: seriesData,
          top: '5%',
          left: '10%',
          bottom: '5%',
          right: '10%',
          symbolSize: 8,
          orient: 'vertical',
          layout: 'orthogonal', // 使用正交布局，减少重叠
          initialTreeDepth: -1, // 默认展开所有节点
          roam: true, // 允许缩放和拖拽
          label: {
            position: 'left',
            verticalAlign: 'middle',
            align: 'right',
            fontSize: 12,
            backgroundColor: 'rgba(255,255,255,0.8)',
            borderRadius: 4,
            padding: [4, 8]
          },
          leaves: {
            label: {
              position: 'right',
              verticalAlign: 'middle',
              align: 'left',
              backgroundColor: 'rgba(255,255,255,0.8)',
              borderRadius: 4,
              padding: [4, 8]
            }
          },
          lineStyle: {
            color: '#ccc',
            width: 2,
            curveness: 0.3 // 增加曲线度，减少线条重叠
          },
          emphasis: {
            focus: 'descendant',
            lineStyle: {
              width: 3,
              color: '#409EFF'
            }
          },
          expandAndCollapse: true,
          animationDuration: 550,
          animationDurationUpdate: 750,
          // 优化布局参数
          nodeAlign: 'justify', // 节点对齐方式
          force: {
            repulsion: 100, // 增加节点间斥力
            gravity: 0.1, // 减少重力，让节点更分散
            edgeLength: 200, // 增加边长度
            layoutAnimation: true
          }
        }]
      };
      
      this.chart.setOption(option);
    },
    
    convertToEChartsData(data) {
      const convertNode = (node) => {
        // 构建简洁的节点显示名称
        let displayName = node.name;
        
        // 添加配偶信息（简化显示）
        if (node.spouses && node.spouses.length > 0) {
          const spouseNames = node.spouses.map(spouse => spouse.spouseName).join('、');
          displayName += ` (${spouseNames})`;
        }
        
        // 添加性别和世代信息（简化）
        const genderText = node.gender === 'M' ? '♂' : node.gender === 'F' ? '♀' : '';
        const generationText = node.generation ? `${node.generation}代` : '';
        const statusText = node.status === '在世' ? '' : node.status;
        
        const fullName = `${displayName} ${genderText} ${generationText} ${statusText}`.trim();
        
        const result = {
          name: fullName,
          value: node.id,
          children: [],
          itemStyle: {
            color: node.gender === 'M' ? '#409EFF' : '#E6A23C'
          }
        };
        
        if (node.children && node.children.length > 0) {
          result.children = node.children.map(child => convertNode(child));
        }
        
        return result;
      };
      
      return data.map(node => convertNode(node));
    },
    
    handleContextMenu(params) {
      // 处理右键菜单
      this.contextMenu.visible = true;
      this.contextMenu.x = params.event.offsetX;
      this.contextMenu.y = params.event.offsetY;
    },
    
    hideMenu() {
      this.contextMenu.visible = false;
    },
    
    handleMouseMove(event) {
      if (this.dragState.dragging) {
        this.dragState.mouseX = event.clientX;
        this.dragState.mouseY = event.clientY;
      }
    },
    
    handleMouseUp() {
      this.dragState.dragging = false;
    },
    
    onMenu(action) {
      // 处理菜单操作
      console.log('Menu action:', action, this.contextMenu.node);
      this.hideMenu();
    }
  }
};
</script>

<style scoped>
.tree-graph-container {
  padding: 20px;
}

.tree-chart-container {
  height: 800px; /* 增加高度，给更多空间 */
  width: 100%;
  position: relative;
  overflow: hidden; /* 防止内容溢出 */
}

.loading-container {
  text-align: center;
  padding: 100px 0;
}

.loading-container i {
  font-size: 48px;
  color: #409EFF;
  animation: rotate 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.empty-container {
  text-align: center;
  padding: 100px 0;
  color: #909399;
}

.empty-container i {
  font-size: 48px;
  margin-bottom: 20px;
}

.context-menu {
  position: absolute;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  padding: 5px 0;
  margin: 0;
  list-style: none;
  z-index: 1000;
}

.context-menu li {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
}

.context-menu li:hover {
  background-color: #f5f7fa;
}

.drag-hint {
  position: fixed;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  padding: 4px 12px;
  border-radius: 4px;
  color: #d48806;
  pointer-events: none;
  z-index: 2000;
}

/* 优化ECharts容器样式 */
.tree-chart-container >>> .echarts-for-vue {
  width: 100% !important;
  height: 100% !important;
}

/* 确保图表响应式 */
.tree-chart-container >>> canvas {
  width: 100% !important;
  height: 100% !important;
}
</style> 